package com.brian.mongo.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @program: architect
 * @author: Brian huang
 * @create: 2019-05-16 14:56
 **/
public class JwtFilter extends GenericFilterBean {

    //校验token
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpSeq = (HttpServletRequest) servletRequest;
        HttpServletResponse httpSes = (HttpServletResponse) servletResponse;

        //Authorization Bearer "token"
        String authHeader = httpSeq.getHeader("authorization");
        Map<String, String[]> authBody = httpSeq.getParameterMap();



        if(StringUtils.isEmpty(authHeader) || !authHeader.startsWith("Bearer")){
            throw new ServletException("Missing or Invalid Authorization Header~");
        }
        String token = authHeader.substring(7);

        Claims claims = Jwts.parser()
                            .setSigningKey("secretkey")
                            .parseClaimsJws(token)
                            .getBody();

        httpSeq.setAttribute("claims", claims);

        filterChain.doFilter(servletRequest,servletResponse);

    }
}
